/*
	Copyright (C) 2008 by Jean-François Geyelin
	jfgeyelin@gmail.com

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the
	Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/


#include "StreamHandler.h"

bool StreamHandler::readNextCharacterInFile(FILE *f, unsigned char *n) {
    int v = fgetc(f);
	if (v==EOF)
	return false;
    *n = (unsigned char)v;
    return true;
}


bool StreamHandler::readString(FILE *f,std::string *str) {
	*str="";
	 char c=fgetc(f);
#ifdef __WIN32__
	while ((c==' ' || c=='\n' || c=='\t') && c != EOF)
#else
	while ((c==' ' || c=='\n' || c=='\t' || c=='\r') && c != EOF)
#endif
	c=fgetc(f);

	if (c==EOF)
	return false;
	do {
		*str+=c;
		c=fgetc(f);
	} while (c!=',' && c!=EOF);

	while ((*str)[str->length()-1]==' ' || (*str)[str->length()-1]=='\n' || (*str)[str->length()-1]=='\t')
	str->resize(str->length()-1);

	return true;
}

bool StreamHandler::readLong(FILE *f, long *n) {
	std::string str;
	if (!readString(f,&str))
	return false;
	*n = (int)atol(str.c_str());
    return true;
}

bool StreamHandler::readFloat(FILE *f, float *n) {
	std::string str;
	if (!readString(f,&str)) {
        LOG_ERROR("failed to read float.\n")
        return false;
	}
	TEST_EXECUTION()
	*n = atof(str.c_str());
    return true;
}

bool StreamHandler::readStructure(FILE *f, char *structure, int size) {
	long n;
	//int i;
	StreamHandler::readLong(f,&n);
	if (n!=size) {
		return false;
	}
	for (int i=0;i<size;i++) {
		StreamHandler::readLong(f,&n);
		structure[i] = (char)n;
	}
	return true;
}


void StreamHandler::writeStructure(FILE *f, char *structure, int size) {
    fprintf(f,"\n%i,\n",size);
	for (int i=0;i<size;i++) {
		fprintf(f,"%i,",structure[i]);
	}
}

void StreamHandler::writeNextCharacterInFile(FILE *f, unsigned char c) {
    fprintf(f,"%c",c);
}

void StreamHandler::writeInt(FILE *f, int n) {
    fprintf(f,"%i,",n);
}

void StreamHandler::writeString(FILE *f, std::string s) {
    fprintf(f,"%s,",s.c_str());
}


